﻿using PLCS.Domain.Menus;
using PLCS.Domain.Roles;
using PLCS.Shared.Common.Unitls;

namespace PLCS.Domain.Users;

public class User : BaseEntity
{
    /// <summary>
    /// 姓名
    /// </summary>
    [Description("姓名")]
    public string Name { get; set; }

    /// <summary>
    /// 用户名
    /// </summary>
    [Description("用户名")]
    public string UserName { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    [Description("密码")]
    private string PassWord;

    /// <summary>
    /// 权限集合（逻辑外键，用分号隔开）
    /// </summary>
    [Description("权限集合")]
    public string? RolesString { get; set; }

    [NotMapped]
    public List<Role>? Roles { get; set; }

    [NotMapped]
    public List<Menu>? Menus { get; set; }

    public User()
    {
    }

    public User(string name, string userName, string passWord, string? rolesString = null)
    {
        Name = name;
        UserName = userName;
        PassWord = PasswordUnitl.GetMd5(passWord);
        RolesString = rolesString;

        CreationTime = DateTime.Now;
    }

    public void AddRole(Role role)
    {
        if (string.IsNullOrEmpty(RolesString))
            RolesString += $"{role.RoleName}";
        else
            RolesString += $"{ConstantChar.SplitChar}{role.RoleName}";
    }

    public void AddRoles(List<Role> roles)
    {
        foreach (var item in roles)
        {
            if (string.IsNullOrEmpty(RolesString))
                RolesString += $"{item.RoleName}";
            else
                RolesString += $"{ConstantChar.SplitChar}{item.RoleName}";
        }
    }

    public IEnumerable<string> Analysis()
    {
        List<string> analysis = new List<string>();
        if (string.IsNullOrEmpty(RolesString))
            return analysis;
        else
        {
            foreach (var item in RolesString.Split(ConstantChar.SplitChar))
            {
                analysis.Add(item);
            }
        }

        return analysis;
    }

    public void ChangePassWord(string value)
    {
        if (value.Length <= 3)
        {
            throw new ArgumentException("密码长度不能小于3");
        }
        PassWord = PasswordUnitl.GetMd5(value);
    }

    public bool CheckPassWord(string value)
    {
        return PassWord == PasswordUnitl.GetMd5(value);
    }
}